package cn.edu.tju.scs.leave.web;

import cn.edu.tju.scs.leave.dto.BizCode;
import cn.edu.tju.scs.leave.dto.ResponseCode;
import cn.edu.tju.scs.leave.dto.UserCurrent;
import cn.edu.tju.scs.leave.entity.User;
import cn.edu.tju.scs.leave.exception.UserException;
import cn.edu.tju.scs.leave.service.UserService;
import cn.edu.tju.scs.leave.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by haoxiaotian on 2016/9/3 2:21.
 */
@Controller
@RequestMapping(value = "/users",method = RequestMethod.GET)
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/entry",method = RequestMethod.POST)
    public @ResponseBody
    ResponseCode<UserCurrent> login(@RequestParam(value = "username",required = false) String username,
                                    @RequestParam(value = "password",required = false) String password,HttpSession session){
        User user = userService.hasMathUser(username,password);
        if(user == null){
            throw new UserException(UserException.WRONG_USER_EXCEPTION);
        }
        if(PasswordUtil.isValid(password,user.getSalt(),user.getPassword())){
            session.setAttribute("user",new User(user.getId(),user.getIdCard(),user.getPhone(),username));
            return new ResponseCode<UserCurrent>(BizCode.SUCCESS,new UserCurrent(user.getId(),user.getIdCard(),user.getPhone(),user.getUsername()));
        }else{
            throw new UserException(UserException.WRONG_USER_EXCEPTION);
        }
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public @ResponseBody
    ResponseCode<String> logout(HttpSession session){
            session.setAttribute("user",null);
            return new ResponseCode<String>(BizCode.SUCCESS,"注销成功");

    }
}
